package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// 绑定 FORM / JSON / XML
type Login struct {
	User     string `form:"user" json:"user" xml:"user"  binding:"required"`
	Password string `form:"password" json:"password" xml:"password" binding:"required"`
	// Birthday time.Time `form:"birthday" json:"birthday" xml:"birthday" time_format:"2006-01-02" time_utc:"1"`
}

// 示例1.设置与获取 Cookie Handler
func getCookieHandler(c *gin.Context) {
	// 获取 cookies 中 secret 字段信息
	secret, err := c.Cookie("secret")
	// 判断 获取cookies 是否有误
	if err == nil {
		// 设置 Cookies：SetCookie(name string, value string, maxAge int, path string, domain string, secure bool, httpOnly bool)
		c.SetCookie("gin_cookie", "test", 3600, "/", "blog.weiyigeek.top", false, true)
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"data": gin.H{
				"secret": secret,
			},
		})
	} else {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    0,
			"message": "请求参数有误!",
		})
	}
}

// 示例2.设置与获取 header Handler
func getHeaderHandler(c *gin.Context) {
	// 获取 header 中 secret 字段信息
	secret := c.GetHeader("secret")
	// 判断 获取 header 是否为空
	if secret != "" {
		// 设置 header (key string, value string)
		c.Header("gin_header", "blog.weiyigeek.top")
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"data": gin.H{
				"secret": secret,
			},
		})
	} else {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    0,
			"message": "请求参数有误!",
		})
	}
}

func main() {
	// Default返回一个Engine实例，该实例已连接Logger和Recovery中间件。
	r := gin.Default()

	// 示例1.设置与获取 Cookie
	r.GET("/cookie_get", getCookieHandler)

	// 示例2.设置与获取 Header
	r.GET("/header_get", getHeaderHandler)

	// Listen and Server in 0.0.0.0:8080
	r.Run(":8080")
}
